package com.ywqf_api.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ywqf_api.base.BaseAPPExcution;
import com.ywqf_api.base.BaseController;
import com.ywqf_api.common.pay.wechat.WechatPayUtil;
import com.ywqf_api.dto.exc.WechatPayExcution;
import com.ywqf_api.dto.in.OrderParDto;
import com.ywqf_api.entity.WechatOrderResult;
import com.ywqf_api.enums.WechatPayEnum;
import com.ywqf_api.service.WechatPaymentService;

@Controller
    @RequestMapping("wechatPayment")
@Api(description = "支付相关",produces = "application/json")
public class WechatPaymentController extends BaseController{

    @Autowired
    private WechatPaymentService wechatPaymentService;


    @RequestMapping(value="unifiedorder", method= RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "统一下单", httpMethod = "GET", notes = "统一下单")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType = "string", name = "userId", value = "用户id", required = true),
            @ApiImplicitParam(paramType = "header", dataType = "string", name = "token", value = "登录凭证", required = true)})
    public BaseAPPExcution unifiedorder(OrderParDto orderParDto){
        //生成订单 返回订单编号
        String insrtPaymentBill = wechatPaymentService.insrtPaymentBill(orderParDto);
        String name = orderParDto.getName();
        String appName = "云网全房" + "-" + name;
        String outTradeNo = insrtPaymentBill;
        int totalFee = orderParDto.getPrice().multiply(new BigDecimal(100)).intValue();
        String body = appName;
        String spbillCreateIp = getSpbillCreateIp();
        WechatOrderResult result = WechatPayUtil.appOrder(body, outTradeNo, totalFee, spbillCreateIp);

        if (!WechatPayUtil.isSuccess(result)) {
            new WechatPayExcution(WechatPayEnum.FAILED);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("统一下单接口返回数据：" + result);
        }
        Map<String, String> apiResult = new HashMap<String, String>();
        apiResult.put("prepayid", result.getPrepayId());
        WechatPayUtil.appSign(apiResult);
        return new WechatPayExcution(WechatPayEnum.SUCCESS, apiResult);
    }
    
    @RequestMapping(value="webhook")
    public void webhook(HttpServletRequest request, HttpServletResponse response){
    	response.setCharacterEncoding("UTF-8");
		StringBuffer xmlStr = new StringBuffer();
		try {
			BufferedReader reader = request.getReader();
			String line = null;
			while ((line = reader.readLine()) != null) {
				xmlStr.append(line);
			}
			if (logger.isDebugEnabled()) {
				logger.debug("支付回调通知：" + xmlStr.toString());
			}
			//验签，通过后查看返回数据是否成功，成功的话继续执行业务逻辑
			response.getWriter().write(returnXML("SUCCESS"));
		} catch (Exception e){
			logger.error("", e);
			try {
				response.getWriter().write(returnXML("FAIL"));
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
    }

    /**
     * 获取客户端ip
     * @return
     */
    private String getSpbillCreateIp(){
        HttpServletRequest request = this.getRequest();
        return request.getRemoteAddr();
    }

    private String returnXML(String return_code) {
		return "<xml><return_code><![CDATA["
		+ return_code
		+ "]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
	}
}
